package com.vinci.task.service.impl;

import com.vinci.login.entity.TbLoginUser;
import com.vinci.task.entity.TbSysDictionaries;
import com.vinci.task.entity.TbTaskCompletedBy;
import com.vinci.task.entity.TbTaskInfo;
import com.vinci.task.mapper.TbTaskCompletedByMapper;
import com.vinci.task.mapper.TbTaskInfoMapper;
import com.vinci.task.service.TbTaskInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 任务表 服务实现类
 * </p>
 *
 * @author 张先生
 * @since 2021-12-11
 */
@Service
public class TbTaskInfoServiceImpl extends ServiceImpl<TbTaskInfoMapper, TbTaskInfo> implements TbTaskInfoService {

    @Autowired(required = false)
    private TbTaskInfoMapper tbTaskInfoMapper;
    @Autowired(required = false)
    private TbTaskCompletedByMapper tbTaskCompletedByMapper;

    /**
     * 根据id查询详情信息
     * @param taskId
     * @return
     */
    @Override
    public List<TbTaskInfo> getById(String taskId) {
        List<TbTaskInfo> list = null;
        try {
            list = tbTaskInfoMapper.getById(taskId);
        } catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 查询任务表信息
     * @param task
     * @return
     */
    @Override
    public List<TbTaskInfo> selectTbTaskInfo(TbTaskInfo task) {

        List<TbTaskInfo> tbTaskInfos = null;
        try {
            tbTaskInfos = tbTaskInfoMapper.selectTbTaskInfo(task);
            for(TbTaskInfo zzk:tbTaskInfos){
                String taskId = zzk.getTaskId();
                String zzl="";
                List<TbTaskCompletedBy> tbTaskCompletedBy = tbTaskInfoMapper.selectTaskCompletedBy(taskId);
                for(TbTaskCompletedBy zkk:tbTaskCompletedBy){
                    String userId = zkk.getUserId();
                    TbLoginUser tbLoginUser = tbTaskInfoMapper.selectUser(userId);
                    String realName = tbLoginUser.getRealName();

                    zzl+=realName+",";
                }
                if( zzl != ""){
                    String substring = zzl.substring(0, zzl.length()-1);
                    zzk.setCompletedBy(substring);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tbTaskInfos;
    }

    /**
     * 添加任务表信息
     * @param task
     * @param session
     * @return
     */
    @Override
    public void insertTbTaskInfo(TbTaskInfo task, HttpSession session) {

        try {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            task.setTaskId(uuid);

            Integer taskType = task.getTaskType();

            TbLoginUser user = (TbLoginUser) session.getAttribute("user");
            String userId = user.getUserId();
            String realName = user.getRealName();
            task.setCreateBy(userId);
            task.setDelflag(0);

            task.setCreateTime(new Timestamp(System.currentTimeMillis()));
            task.setUpdateTime(new Timestamp(System.currentTimeMillis()));


            TbLoginUser tbLoginUser = tbTaskInfoMapper.selectUser(userId);
            String realName1 = tbLoginUser.getRealName();

            // 1. 创建ProcessEngine
            ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
            // 2. 获取RunTimeService
            RuntimeService runtimeService = processEngine.getRuntimeService();
            // 流程定义的key
            String key = "task_info";
            // 流程变量的map
            Map<String,Object> variables = new HashMap<>();
            if(taskType == 1){
                // 设定任务的负责人
                variables.put("assignee0",userId);
                variables.put("assignee1",realName1);
                variables.put("assignee2",realName1);
            }else {
                // 设定任务的负责人
                variables.put("assignee0",realName);
                variables.put("assignee1",realName);
                variables.put("assignee2",realName);
            }
            // 3. 根据流程定义 Id启动流程
            runtimeService.startProcessInstanceByKey(key,variables);

            // 1:指定；2：认领；3：自荐
            if(taskType == 1){
                //3.进行中
                task.setStatus(3);
                TbTaskCompletedBy tbTaskCompletedBy = new TbTaskCompletedBy();
                tbTaskCompletedBy.setUserId(userId);
                tbTaskCompletedBy.setTaskId(uuid);
                tbTaskCompletedBy.setCreateTime(new Timestamp(System.currentTimeMillis()));
                tbTaskCompletedBy.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                tbTaskCompletedBy.setCreateBy(userId);
                tbTaskCompletedBy.setDelflag(0);
                tbTaskCompletedByMapper.insertTbTaskCompletedBy(tbTaskCompletedBy);

                // 获取taskService
                TaskService taskService = processEngine.getTaskService();

                //根据流程key 和 任务负责人 查询任务
                // 返回一个任务对象
                Task task2 = taskService.createTaskQuery()
                        .processDefinitionKey("task_info") //流程key
                        .taskAssignee(realName) //要查询的负责人
                        .singleResult();

                if(task2 != null){
                    // 根据任务id来   完成任务
                    taskService.complete(task2.getId());
                }

            }else if(taskType == 2){
                //1.待认领
                task.setStatus(1);
            }else if(taskType == 3){
                //2.比拼中
                task.setStatus(2);
            }

            tbTaskInfoMapper.insertTbTaskInfo(task);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 修改任务表信息
     * @param task
     * @return
     */
    @Override
    public void updateTbTaskInfo(TbTaskInfo task) {

        try {
            Integer taskType = task.getTaskType();
            // 1:指定；2：认领；3：自荐
            if(taskType == 1){
                //3.进行中
                task.setStatus(3);
                String createBy = task.getCreateBy();

                // 1. 创建ProcessEngine
                ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
                // 获取taskService
                TaskService taskService = processEngine.getTaskService();

                //根据流程key 和 任务负责人 查询任务
                // 返回一个任务对象
                Task task2 = taskService.createTaskQuery()
                        .processDefinitionKey("task_info") //流程key
                        .taskAssignee(createBy) //要查询的负责人
                        .singleResult();

                if(task2 != null){
                    // 根据任务id来   完成任务
                    taskService.complete(task2.getId());
                }

            }else if(taskType == 2){
                //1.待认领
                task.setStatus(1);
            }else if(taskType == 3){
                //2.比拼中
                task.setStatus(2);
            }
            task.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            tbTaskInfoMapper.updateTbTaskInfo(task);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 删除任务表信息
     * @param taskId
     * @return
     */
    @Override
    public void deleteTbTaskInfo(String taskId) {

        try {
            tbTaskInfoMapper.deleteTbTaskInfo(taskId);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 查询任务设置类型
     * @return
     */
    @Override
    public List<TbSysDictionaries> selectCategory() {
        List<TbSysDictionaries> tbSysDictionaries = null;
        try {
            tbSysDictionaries = tbTaskInfoMapper.selectCategory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tbSysDictionaries;
    }

    /**
     * 认领任务
     * @param task
     * @param session
     */
    @Override
    public void updateClaim(TbTaskInfo task,HttpSession session) {

        try {
            List<TbTaskInfo> tbTaskInfos = tbTaskInfoMapper.selectTbTaskInfo(task);
            for(TbTaskInfo zzk : tbTaskInfos){
                String createBy = zzk.getCreateBy();
                TbLoginUser tbLoginUser = tbTaskInfoMapper.selectUser(createBy);
                String realName1 = tbLoginUser.getRealName();
                // 1. 创建ProcessEngine
                ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
                // 获取taskService
                TaskService taskService = processEngine.getTaskService();

                TbLoginUser user = (TbLoginUser) session.getAttribute("user");
                String realName = user.getRealName();
                //根据流程key 和 任务负责人 查询任务
                // 返回一个任务对象
                Map<String,Object> map = new HashMap<>();
                // 把流程变量的pojo放入map
                map.put("assignee1",realName);
                map.put("assignee2",realName);

                Task task2 = taskService.createTaskQuery()
                        .processDefinitionKey("task_info") //流程key
                        .taskAssignee(realName1) //要查询的负责人
                        .singleResult();

                if(task2 != null){
                    // 根据任务id来   完成任务
                    taskService.complete(task2.getId(),map);
                }
            }

            tbTaskInfoMapper.updateClaim(task);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 指定任务人
     * @param task
     */
    @Override
    public void updateDesignee(TbTaskInfo task) {
        try {
            task.setStatus(3);
            String createBy = task.getCreateBy();
            TbLoginUser tbLoginUser2 = tbTaskInfoMapper.selectUser(createBy);
            String realName1 = tbLoginUser2.getRealName();
            // 1. 创建ProcessEngine
            ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
            // 获取taskService
            TaskService taskService = processEngine.getTaskService();

            String userId = task.getUserId();
            TbLoginUser tbLoginUser = tbTaskInfoMapper.selectUser(userId);
            String realName = tbLoginUser.getRealName();

            //根据流程key 和 任务负责人 查询任务
            // 返回一个任务对象
            Map<String,Object> map = new HashMap<>();
            // 把流程变量的pojo放入map
            map.put("assignee1",realName);
            map.put("assignee2",realName);

            Task task2 = taskService.createTaskQuery()
                    .processDefinitionKey("task_info") //流程key
                    .taskAssignee(realName1) //要查询的负责人
                    .singleResult();

            if(task2 != null){
                // 根据任务id来   完成任务
                taskService.complete(task2.getId(),map);
            }

            tbTaskInfoMapper.updateClaim(task);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
